package ndquangr.intern.ringtonemaker;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import ndquangr.intern.ringtonemaker.listitems.BrowseCateAdapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ListView;

public class BrowseActivity extends Activity {
	private ListView lsv_browse_categories;
	private BrowseCateAdapter adtCategories;	
	private List<String> listItems;
	private boolean isFirstBrowseScreen;
	private Context mContext;
	private String sCurrentCategory;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.browse_window);
        mContext = this;
        
        lsv_browse_categories = (ListView)findViewById(R.id.lsv_browse_musicCategories);
                
		isFirstBrowseScreen = true;		
		listItems = new ArrayList<String>();
		listItems.addAll(Arrays.asList(Constants.MUSIC_CATEGORIES)) ;
		
		adtCategories = new BrowseCateAdapter(this, R.layout.browse_cate_item, new ArrayList<String>(listItems));
		
		if (adtCategories != null) {
			lsv_browse_categories.setAdapter(adtCategories);			
		}		
		lsv_browse_categories.setOnItemClickListener(lsItemClick);
    }
    
	private List<String> getAllFolders() {
		//Some audio may be explicitly marked as not being music
		
		String[] projection = {
				"DISTINCT " + MediaStore.Audio.Media.DATA
		};
	
		Cursor cursor = this.managedQuery(
		        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
		        projection,
		        null,
		        null,
		        MediaStore.Audio.Media.DATA);
	
		ArrayList<String> items = new ArrayList<String>();
		String item, new_item;
		String splited_item [];
		int splited_part;
		while(cursor.moveToNext()){		 
			item = cursor.getString(0);
			splited_item = item.split("/");
			splited_part = splited_item.length;
			if (splited_part > 2) {
				new_item = "";
				for (int i = 2; i < splited_part - 1; i++) {
					new_item = new_item + splited_item[i];
					if (i < splited_part - 2) {
						new_item = new_item + "/";
					}
				}		
				if (!new_item.equals("") && !items.contains(new_item)) {
					items.add(new_item);
				}
			}			
		}

		return items;
	}
	
	private List<String> getAllGenres() {
		
		String[] projection = {
				"DISTINCT " + MediaStore.Audio.Genres.NAME
		};
	
		Cursor cursor = this.managedQuery(
				MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI,
		        projection,
		        null,
		        null,
		        MediaStore.Audio.Genres.NAME);
		ArrayList<String> items = new ArrayList<String>();
		while(cursor.moveToNext()){		    
			items.add(cursor.getString(0));
		}
		
		return items;
	}
	
	private List<String> getAllAlbums() {
		//Some audio may be explicitly marked as not being music
		String[] projection = {
				"DISTINCT " + MediaStore.Audio.Media.ALBUM
		};
	
		Cursor cursor = this.managedQuery(
		        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
		        projection,
		        null,
		        null,
		        MediaStore.Audio.Media.ALBUM);
		ArrayList<String> items = new ArrayList<String>();
		while(cursor.moveToNext()){		    
			items.add(cursor.getString(0));
		}
		return items;
	}
	
	private List<String> getAllArtists() {
		//Some audio may be explicitly marked as not being music
		
		String[] projection = {
				"DISTINCT " + MediaStore.Audio.Media.ARTIST
		};
	
		Cursor cursor = this.managedQuery(
		        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
		        projection,
		        null,
		        null,
		        MediaStore.Audio.Media.ARTIST);
		ArrayList<String> items = new ArrayList<String>();
		while(cursor.moveToNext()){		    
			items.add(cursor.getString(0));
		}
		
		return items;
	}
	
	private OnItemClickListener lsItemClick = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> adapter, View view,
                int position, long id) {
        		if (isFirstBrowseScreen) {
        			if (position == 0) {					
						goAllSongList();
        			} else if ((position > 0) && (position <5)) {
        				sCurrentCategory = listItems.get(position);
        				switch (position) {
						case 1:
							listItems = getAllArtists();
							break;
						case 2:
							listItems = getAllAlbums();
							break;
						case 3:
							listItems = getAllGenres();
							break;
						case 4:
							listItems = getAllFolders();
							break;

						default:
							break;
						}
        				if (listItems != null) {
        					isFirstBrowseScreen = false;
        					adtCategories = new BrowseCateAdapter(mContext, R.layout.browse_cate_item, new ArrayList<String>(listItems));        					
        					lsv_browse_categories.setAdapter(adtCategories);	
        				}
        			} else if (position == 5) {
						goMyRingtoneList();
        			}
        		} else {        			
        			goSpecificCate(sCurrentCategory, listItems.get(position));
        		}
          }

		
      };
      
   // Go to view all songs
  	protected void goAllSongList() {
  		Intent myIntent = new Intent(mContext, AllSongListActivity.class);
  		mContext.startActivity(myIntent);
  	}
  	
  	// Go to view all songs in default directory
	private void goMyRingtoneList() {
		Intent myIntent = new Intent(mContext, AllSongListActivity.class);
		myIntent.putExtra("category", Constants.MUSIC_CATEGORIES[5]);
		mContext.startActivity(myIntent);
	}	
	
	private void goSpecificCate(String cate, String cateDetail) {
		Intent myIntent = new Intent(mContext, AllSongListActivity.class);
		myIntent.putExtra("category", cate);
		myIntent.putExtra("category_name", cateDetail);
		mContext.startActivity(myIntent);
	}
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        	if (!isFirstBrowseScreen) {
        		isFirstBrowseScreen = true;
        		listItems = new ArrayList<String>();
        		listItems.addAll(Arrays.asList(Constants.MUSIC_CATEGORIES)) ;
        		
        		adtCategories = new BrowseCateAdapter(this, R.layout.browse_cate_item, new ArrayList<String>(listItems));
        		
        		if (adtCategories != null) {
        			lsv_browse_categories.setAdapter(adtCategories);			
        		}		
        		return true;
        	} else {
        		return super.onKeyDown(keyCode, event);
        	}
        }
        return super.onKeyDown(keyCode, event);
    }
}
